<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <title>Spring Boot WebSocket 点对点</title>
</head>
<body onload="CHAT.close()">
<noscript>
    <h2 style="color: #ff0000;">貌似你的浏览器不支持 websocket</h2>
</noscript>
<div>
    <label for="selfID">输入你的ID: </label>
    <input type="text" id="selfID" placeholder="你的ID"/>
    <br/>

    <button id="connect" onclick="CHAT.init()">Connect</button>
    <button id="disconnect" onclick="CHAT.close();" disabled="disabled">Disconnect</button>
</div>
<div id="conversationDiv">
    <label for="chatUserID">接收方ID: </label>
    <input type="text" name="用户名：" id="chatUserID" placeholder="接收方ID"/>
    <br/>
    <label for="message">Message: </label>
    <input type="text" id="message" placeholder="输入消息内容"/>
    <button id="sendName" onclick="CHAT.chat();">发送</button>
    <p id="response"></p>
</div>
<script th:src="@{../jquery.min.js}"></script>
<script type="text/javascript">
    var selfID = null;

    /**
     * 连接im服务流程:
     * 1. client请求对应业务服务
     * 2. 业务服务请求IM系统,获取token
     * 3. IM系统保存token,并根据业务传过来的有效时间设置token有效期
     * 4. 将token返回给客户端
     * 2. client根据token连接服务
     */
    window.CHAT = {
        serverUrl: "localhost/",
        socket: null,
        init: function () {
            if (window.WebSocket) {
                // 如果当前的状态已经连接，那就不需要重复初始化websocket
                if (CHAT.socket != null
                    && CHAT.socket != undefined
                    && CHAT.socket.readyState == WebSocket.OPEN) {
                    return false;
                }
                //首先获取token
                selfID = $("#selfID").val();
                $.ajax({
                    url: "http://" + CHAT.serverUrl + "auth/token",
                    type: "PUT",
                    data: {userId: selfID},
                    dataType: "json",
                    success: function (result) {
                        if (result.retCode === 10000) {
                            //通过token  建立连接
                            var token = result.obj
                            if ('WebSocket' in window) {
                                CHAT.socket = new WebSocket("ws://" + CHAT.serverUrl + "/socketServer/" + token);
                            }
                            else if ('MozWebSocket' in window) {
                                CHAT.socket = new MozWebSocket("ws://" + CHAT.serverUrl + "/socketServer/" + token);
                            }
                            else {
                                alert("该浏览器不支持websocket");
                            }
                            CHAT.socket.onopen = CHAT.open;
                            CHAT.socket.onclose = CHAT.close;
                            CHAT.socket.onerror = CHAT.error;
                            CHAT.socket.onmessage = CHAT.message;
                        }
                    }
                })
            } else {
                alert("不支持websocket");
            }
        },
        //open事件  建立连接后
        open: function () {
            console.log("websocket连接已建立...");
            setConnected(true);
            // 定时发送心跳
            CHAT.heartCheck();
        },
        //接收消息
        message: function (e) {
            var response = $('#response');
            console.log(JSON.stringify(e));
            console.log(JSON.stringify(e.data));
            var data = JSON.parse(e.data)
            if (data.action !== 0) {
                response.html(e.data);
            }
        },
        //发送消息
        chat: function () {
            //这里要拼接成后台要求的格式,
            var body = {
                to: $('#chatUserID').val(),
                msg: $('#message').val(),
                save: false
            };
            var message = {
                v: 1.0,
                body: body,
                action: 1
            };
            // 如果当前websocket的状态是已打开，则直接发送， 否则重连
            if (CHAT.socket != null
                && CHAT.socket != undefined
                && CHAT.socket.readyState == WebSocket.OPEN) {
                var json = JSON.stringify(message);
                console.log("发送消息:"+ json)
                CHAT.socket.send(json);
            } else {
                // 重连websocket
                CHAT.open();
                setTimeout("CHAT.reChat('" + JSON.stringify(body) + "')", "1000");
            }
        },
        //重新发送
        reChat: function (msg) {
            console.log("消息重新发送...");
            CHAT.socket.send(msg);
        },
        close: function () {
            if (CHAT.socket != null) {
                CHAT.socket.close();
            }
            setConnected(false);
            console.log('Disconnected');
        },
        error: function () {
            console.log("error");
        },
        heartCheck: function () {
            setTimeout(function () {
                var ping = {
                    v: 1.0,
                    action: 0
                };
                CHAT.socket.send(JSON.stringify(ping));
                console.log('heartCheck');
                CHAT.heartCheck();
            }, 10000)
        }
    };


    function setConnected(connected) {
        var conn = $('#connect');
        var disconn = $('#disconnect');
        if (connected) {
            conn.attr('disabled', 'true');
            disconn.removeAttr('disabled');
        } else {
            conn.removeAttr('disabled');
            disconn.attr('disabled', 'true');
        }
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }

</script>
</body>
</html>